# -*- coding: UTF-8 -*-

import logging
import logging.config
import pylog_handler
import pylog_formatter
import jkzuc

JakaLogRotationHandler = pylog_handler.JakaLogRotationHandler
JakaLogFormatter = pylog_formatter.JakaLogFormatter

_LOG_CONFIG = {
    "version": 1,
    "disable_existing_loggers": True,
    "formatters": {
        "default": {
            # 使用自定义的日志Formatter
            "()": "pylog.JakaLogFormatter",
            "format": "%(levelname)s %(asctime)s:%(msecs)03d000 [%(process)d:%(thread)d] [%(name)s] %(message)s",
            "datefmt": "%Y\%m\%d %H:%M:%S",
        },
        "log_format_0": {
            # "format": "[%(asctime)s][%(levelname)s][%(filename)s:%(lineno)s]"
            # "[%(process)d] %(message)s",
            # 使用自定义的日志Formatter
            "()": "pylog.JakaLogFormatter",
            "format": "%(levelname)s %(asctime)s:%(msecs)03d000 [%(process)d:%(thread)d] [%(name)s] %(message)s",
            "datefmt": "%Y\%m\%d %H:%M:%S",
        },
    },
    # Set up our concurrent logger handler. Need one of these per unique file.
    "handlers": {
        # 配置SDK日志
        "sdk_log": {
            "level": "DEBUG",
            # 使用自定义的日志Handler
            "class": "pylog.JakaLogRotationHandler",
            # Example of a custom format for this log.
            "formatter": "log_format_0",
            # 'formatter': 'default',
            "filename": jkzuc.jkroot_dir + "/scripts/log/sdk.log",
            # Optional: set an owner and group for the log file
            # 'owner': ['greenfrog', 'admin'],
            # Sets permissions to owner and group read+write
            "chmod": 0o0660,
            # Note: this is abnormally small to make it easier to demonstrate rollover.
            # A more reasonable value might be 10 MiB or 10485760
            # 限制单个日志大小20M
            "maxBytes": 2 * 1024 * 1024,
            # Number of rollover files to keep
            "backupCount": 5,
            "use_gzip": True,
        },
        # 配置GRPC日志
        "grpc_log": {
            "level": "DEBUG",
            # 使用自定义的日志Handler
            "class": "pylog.JakaLogRotationHandler",
            # Example of a custom format for this log.
            "formatter": "log_format_0",
            # 'formatter': 'default',
            "filename": jkzuc.jkroot_dir + "/scripts/log/grpc.log",
            # Optional: set an owner and group for the log file
            # 'owner': ['greenfrog', 'admin'],
            # Sets permissions to owner and group read+write
            "chmod": 0o0660,
            # Note: this is abnormally small to make it easier to demonstrate rollover.
            # A more reasonable value might be 10 MiB or 10485760
            # 限制单个日志大小20M
            "maxBytes": 2 * 1024 * 1024,
            # Number of rollover files to keep
            "backupCount": 5,
            "use_gzip": True,
        },
        # 配置输出日志到终端
        "console": {"class": "logging.StreamHandler", "formatter": "default", "level": "DEBUG"},
        "root_log": {
            "level": "DEBUG",
            # 使用自定义的日志Handler
            "class": "pylog.JakaLogRotationHandler",
            # Example of a custom format for this log.
            "formatter": "log_format_0",
            # 'formatter': 'default',
            "filename": jkzuc.jkroot_dir + "/scripts/log/root.log",
            # Optional: set an owner and group for the log file
            # 'owner': ['greenfrog', 'admin'],
            # Sets permissions to owner and group read+write
            "chmod": 0o0660,
            # Note: this is abnormally small to make it easier to demonstrate rollover.
            # A more reasonable value might be 10 MiB or 10485760
            # 限制单个日志大小20M
            "maxBytes": 2 * 1024 * 1024,
            # Number of rollover files to keep
            "backupCount": 5,
            "use_gzip": True,
        },
        "addon_log": {
            "level": "DEBUG",
            # 使用自定义的日志Handler
            "class": "pylog.JakaLogRotationHandler",
            # Example of a custom format for this log.
            "formatter": "log_format_0",
            # 'formatter': 'default',
            "filename": jkzuc.jkroot_dir + "/scripts/log/addon.log",
            # Optional: set an owner and group for the log file
            # 'owner': ['greenfrog', 'admin'],
            # Sets permissions to owner and group read+write
            "chmod": 0o0660,
            # Note: this is abnormally small to make it easier to demonstrate rollover.
            # A more reasonable value might be 10 MiB or 10485760
            # 限制单个日志大小20M
            "maxBytes": 2 * 1024 * 1024,
            # Number of rollover files to keep
            "backupCount": 5,
            "use_gzip": True,
        },
    },
    # Tell root logger to use our concurrent handler
    "root": {
        "handlers": [
            "root_log",
            # 'my_concurrent_log',
            # 在开发时，可以取消这一行, 在终端输出日志
            # 在版本发布时，注释这一行，避免日志输出过量
            "console",
        ],
        "level": "DEBUG",
    },
    "loggers": {
        "SDK": {
            "handlers": [
                # 'console',
                "sdk_log"
            ],
            "level": "DEBUG",
            # 按log命名空间依次传递到root
            "propagate": True,
        },
        "GRPC": {
            "handlers": [
                # 'console',
                "grpc_log"
            ],
            "level": "DEBUG",
            # 按log命名空间依次传递到root
            "propagate": True,
        },
        "pyftpdlib": {
            "handlers": [
                # 'console',
                "grpc_log"
            ],
            "level": "INFO",
            # 按log命名空间依次传递到root
            "propagate": True,
        },
        "CHECK": {
            "handlers": [
                # 'console',
                "grpc_log"
            ],
            "level": "DEBUG",
            # 按log命名空间依次传递到root
            "propagate": True,
        },
        "pylog": {
            "handlers": [],
            "level": "DEBUG",
            # 按log命名空间依次传递到root
            "propagate": True,
        },
        "ADDON_M": {
            "handlers": [
                # 'console',
                "addon_log"
            ],
            "level": "DEBUG",
            # 按log命名空间依次传递到root
            "propagate": True,
        },
    },
}

# import multiprocessing

# class LogWorker(multiprocessing.Process):

#     def __init__(self, logger, id):
#         ps_name = "jaka_logger_{}".format(id)

#         super(LogWorker, self).__init__(name=ps_name)
#         self.ps_name = ps_name
#         self.logger = logger

#     def run(self):
#         for _ in range(10):
#             self.logger.debug("[%s] 1234567890" % self.ps_name)


def setup():
    logging.config.dictConfig(_LOG_CONFIG)
    pylog_logger().debug("setup pylog")


def pylog_logger():
    return logging.getLogger("pylog")


def grpc_logger():
    return logging.getLogger("GRPC")


def grpc_addon_logger():
    return logging.getLogger("GRPC.ADDON")


def tcp_logger():
    return logging.getLogger("SDK")


def check_logger():
    return logging.getLogger("CHECK")


def addon_logger():
    logger = logging.getLogger("ADDON_M")
    if len(logger.handlers) == 0:
        setup()
    return logger

    # logger = logging.getLogger("WoCao")
    # logger.setLevel(logging.DEBUG)

    # worker_list = [LogWorker(logger, id=i) for i in range(10)]
    # for worker in worker_list:
    #     worker.start()

    # for worker in worker_list:
    #     if worker.is_alive():
    #         worker.join()


if __name__ == "__main__":
    setup()
    logger = logging.getLogger("root")
    logger.debug("12345")
    pass
